//
//  HJRegionController.m
//  KaiChat
//
//  Created by lx on 2023/12/20.
//

#import "HJRegionController.h"
#import "HJTitleCell.h"
#import "HJSectionHeaderView.h"
#import "QMUIButton.h"
#import "HJCityController.h"
#import "HJSelectCityCell.h"
#import "HJMinePresent.h"
#import "HJUserModel.h"
#import "HJPositioning.h"

@interface HJRegionController ()<HJPositioningDelegate>

@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, strong) HJPositioning *positioning;
@property (nonatomic, weak) QMUIButton *loctionButton;
@property (nonatomic, assign) NSIndexPath *lastIndexPath;

@end

@implementation HJRegionController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationBar.title = @"Region";
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 90)];
    headerView.backgroundColor = UIColor.whiteColor;
    
    HJSectionHeaderView *locationSectionView = [[HJSectionHeaderView alloc] init];
    locationSectionView.titleLabel.text = @"Location";
    locationSectionView.titleLabel.textColor = UIColor.tj_BEBDCAColor;
    [headerView addSubview:locationSectionView];
    locationSectionView.contentView.backgroundColor = UIColor.tj_F6F6F6Color;
    locationSectionView.backgroundColor = UIColor.tj_F6F6F6Color;
    [locationSectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(0);
        make.height.offset(20);
    }];
    
    UIView *loctionView = [UIView addToView:headerView];
    loctionView.backgroundColor = UIColor.whiteColor;
    [loctionView addTapGesturesWithTarget:self action:@selector(tapLoctionView)];
    [loctionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(0);
        make.top.equalTo(locationSectionView.mas_bottom);
        make.height.offset(50);
    }];
    
    QMUIButton *loctionButton = [QMUIButton buttonWithSuperView:loctionView font:UIFontMake(14) color:UIColor.tj_333333Color title:@""];
    [loctionButton setImagePosition:QMUIButtonImagePositionLeft];
    loctionButton.spacingBetweenImageAndTitle = 6;
    [loctionButton setImage:[UIImage imageNamed:@"location_icon"] forState:UIControlStateNormal];
    [loctionButton sizeToFit];
    [loctionButton addTarget:self action:@selector(tapLoctionView) forControlEvents:UIControlEventTouchUpInside];
    CGFloat loctionButtonW = loctionButton.frame.size.width;
    [loctionButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.inset(leftRightMargin);
        make.width.offset(loctionButtonW);
        make.top.bottom.offset(0);
    }];
    
    HJSectionHeaderView *regionsSectionView = [[HJSectionHeaderView alloc] init];
    regionsSectionView.titleLabel.text = @"All regions";
    regionsSectionView.titleLabel.textColor = UIColor.tj_BEBDCAColor;
    [headerView addSubview:regionsSectionView];
    regionsSectionView.contentView.backgroundColor = UIColor.tj_F6F6F6Color;
    regionsSectionView.backgroundColor = UIColor.tj_F6F6F6Color;
    [regionsSectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(loctionButton.mas_bottom);
        make.height.offset(20);
    }];
    
    _loctionButton = loctionButton;
    
    self.tableView.tableHeaderView = headerView;
    [self.tableView registerClass:HJTitleCell.class forCellReuseIdentifier:@"HJTitleCell"];
    [self.tableView registerClass:HJSelectCityCell.class forCellReuseIdentifier:@"HJSelectCityCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 50;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, TabbarSafeBottomMargin, 0);
    self.tableView.backgroundColor = UIColor.whiteColor;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(KNavBarHight);
        make.bottom.offset(0);
    }];
    
    _positioning = [[HJPositioning alloc] init];
    _positioning.delegate = self;
    [_positioning start];
    [self loadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJCellModel *model = self.datas[indexPath.row];
    if (model.showArrow) {
        HJTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJTitleCell" forIndexPath:indexPath];
        cell.model = self.datas[indexPath.row];
        return cell;
    }
    HJSelectCityCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJSelectCityCell" forIndexPath:indexPath];
    cell.model = self.datas[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HJCellModel *model = self.datas[indexPath.row];
    if (model.showArrow) {
        HJCityController *cityController = [[HJCityController alloc] init];
        cityController.region = self.region;
        cityController.complete = self.complete;
        NSDictionary *anyObject = model.anyObject;
        cityController.selectRegion = anyObject[@"countryName"];
        cityController.citys = anyObject[@"cityList"];
        [self.navigationController pushViewController:cityController];
        return;
    }
    
    model.isSelect = YES;
    
    if (_lastIndexPath) {
        HJSelectCityCell *lastCell = [tableView cellForRowAtIndexPath:_lastIndexPath];
        lastCell.model.isSelect = NO;
        lastCell.model = lastCell.model;
    }
    
    HJSelectCityCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.model = model;
    self.lastIndexPath = indexPath;
    [self editRegion:model.text];
}

- (void)tapLoctionView {
    if ([self.loctionButton.currentTitle isEqualToString:@"Unable to access your location"]) {
        NSURL *appSettings = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:appSettings]) {
            [[UIApplication sharedApplication] openURL:appSettings options:@{} completionHandler:nil];
        }
    }
}

- (void)positioningSucceed:(HJPositioning *)positioning {
    [HJMinePresent getRegionWithLongitude:positioning.longitude latitude:positioning.latitude complete:^(NSString * _Nullable region) {
        [self updateLoctionButtonTitle:region image:[UIImage imageNamed:@"location_icon"]];
    }];
}

- (void)updateLoctionButtonTitle:(NSString *)title image:(UIImage *)image {
    [self.loctionButton setImage:image forState:UIControlStateNormal];
    [self.loctionButton setTitle:title forState:UIControlStateNormal];
    [self.loctionButton sizeToFit];
    CGFloat loctionButtonW = self.loctionButton.frame.size.width;
    [self.loctionButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.inset(leftRightMargin);
        make.width.offset(loctionButtonW);
        make.top.bottom.offset(0);
    }];
}

- (void)positioningFail:(HJPositioning *)positioning error:(NSError *)error {
    [self updateLoctionButtonTitle:@"Unable to access your location" image:[UIImage imageNamed:@"location_error"]];
}

- (void)editRegion:(NSString *)value {
    [HJHUD showLoadingInView:self.view];
    
    [HJMinePresent modifyRegion:value complete:^(NSError * _Nullable error) {
        if (error) {
            [HJHUD showErrorMessage:@"Operation failed"];
            HJSelectCityCell *lastCell = [self.tableView cellForRowAtIndexPath:self.lastIndexPath];
            lastCell.model.isSelect = NO;
            lastCell.model = lastCell.model;
            return;
        }
        
        if (self.complete) {
            self.complete(value);
        }
        
        HJUserModel *userModel = [HJUserModel currentAccountModel];
        userModel.region = value;
        [userModel bg_saveOrUpdateAsync:nil];
        
        [HJHUD showSucceedMessage:@"Successful operation"];
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
}

- (void)loadData {
    dispatch_async_global_queue(^{
        
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"json"];
        NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
        NSArray *datas = [jsonData mj_JSONObject];
        NSMutableArray *Marr = [NSMutableArray array];
        
        __block  HJCellModel *selectCellModel = nil;
        for (NSDictionary *  _Nonnull dict in datas) {
            
            HJCellModel *cellModel = [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.anyObject = dict;
                model.text = dict[@"countryName"];
                if ([dict[@"cityList"] count]) {
                    model.showArrow = YES;
                } else {
                    model.showArrow = NO;
                }
            }];
            
            if ([cellModel.text isEqualToString:self.region]) {
                selectCellModel = cellModel;
            } else {
                for (NSDictionary *obj in dict[@"cityList"]) {
                    if ([self.region containsString:obj[@"cityName"]]) {
                        selectCellModel = cellModel;
                        break;
                    }
                }
            }
            
            [Marr addObject:cellModel];
        }
        
        HJCellModel *secrecyModel = [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
            model.text = @"Secrecy";
            [Marr addObject:model];
        }];
        
        if ([self.region isEqualToString:secrecyModel.text]) {
            selectCellModel = secrecyModel;
        }
        
        dispatch_async_main_queue(^{
            
            if (selectCellModel) {
                selectCellModel.text = self.region;
                selectCellModel.detailText = @"Selected";
                [Marr removeObject:selectCellModel];
                [Marr insertObject:selectCellModel atIndex:0];
     
            } 
            
            if (secrecyModel == Marr.lastObject) {
                secrecyModel.showLine = YES;
                secrecyModel.showArrow = NO;
            }

            self.datas = Marr;
            [self.tableView reloadData];
        });
    });
    
    
}

- (void)dealloc {
    NSLog(@"%s", __func__);
}


@end
